package me.chanjar.weixin.cp.tp.service.impl;

import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor;
import me.chanjar.weixin.cp.bean.WxCpTpContactSearch;
import me.chanjar.weixin.cp.bean.WxCpTpContactSearchResp;
import me.chanjar.weixin.cp.bean.WxCpTpIdTranslate;
import me.chanjar.weixin.cp.bean.WxCpTpIdTranslateResp;
import me.chanjar.weixin.cp.bean.WxCpTpIdTranslateResultResp;
import me.chanjar.weixin.cp.tp.service.WxCpTpContactService;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.MEDIA_UPLOAD;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.CONTACT_SEARCH;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.ID_TRANSLATE;

import java.io.File;

import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.GET_BATCH_RESULT;;

/**
 * @author uianz
 * @description
 * @since 2020/12/23 下午 02:39
 */
@RequiredArgsConstructor
public class WxCpTpContactServiceImpl implements WxCpTpContactService {

  private final WxCpTpService mainService;

  @Override
  public WxCpTpContactSearchResp contactSearch(WxCpTpContactSearch wxCpTpContactSearch) throws WxErrorException {
    String responseText =
      mainService.post(mainService.getWxCpTpConfigStorage().getApiUrl(CONTACT_SEARCH) + "?provider_access_token=" + mainService.getWxCpProviderToken(), wxCpTpContactSearch.toJson());
    return WxCpTpContactSearchResp.fromJson(responseText);
  }
  
  
  /**
   * 上传转译媒体文件
   * */
  @Override
  public WxMediaUploadResult upload(String mediaType, File file) throws WxErrorException {
      return this.mainService.execute(MediaUploadRequestExecutor.create(this.mainService.getRequestHttp()),
        mainService.getWxCpTpConfigStorage().getApiUrl(MEDIA_UPLOAD + mediaType) + "&provider_access_token=" + mainService.getWxCpProviderToken(), file);
  }
  
  /**
   * 提交通讯录id转译
   * */
  @Override
  public WxCpTpIdTranslateResp idTranslate(WxCpTpIdTranslate wxCpTpIdTranslate) throws WxErrorException {
    String responseText =
      mainService.post(mainService.getWxCpTpConfigStorage().getApiUrl(ID_TRANSLATE) + "?provider_access_token=" + mainService.getWxCpProviderToken(), wxCpTpIdTranslate.toJson());
    return WxCpTpIdTranslateResp.fromJson(responseText);
  }
  
  /**
   * 获取异步任务结果
   * */
  @Override
  public WxCpTpIdTranslateResultResp getBatchResult(String jobId) throws WxErrorException {
    String responseText =
      mainService.get(mainService.getWxCpTpConfigStorage().getApiUrl(GET_BATCH_RESULT + jobId) + "&provider_access_token=" + mainService.getWxCpProviderToken(),null);
    return WxCpTpIdTranslateResultResp.fromJson(responseText);
  }
}
